//#include "LibThread.h"
#include "TcpServer.h"
#include <atomic>
#include <iostream>
#include <unistd.h>

struct myTXT {

	std::string s = {0};

};

static void pipe_cb(int fd, short event,void*ptr) {

	struct event* m_pipeEvent = (struct event*)ptr;
	
	//myTXT* m = nullptr;
	
	char s[100] = {0};

	int n = read(fd, (void*)s, sizeof(s));

	std::string* a = (std::string*)s;
	
	std::string c = "close";
	std::string b = "exit";

	if (!a->compare(c)) {

		std::cout << *a << std::endl;
		std::cout << "Thread[" << std::this_thread::get_id() << "] is going to die..." << std::endl;
		event_del(m_pipeEvent);

	}
	else if (!a->compare(b))
	{
		std::cout << *a << std::endl;
	}
	else{

		//std::cout << "Thread[" << std::this_thread::get_id() << "]receive a message from my pipe[" << fd << "]: " << *a << std::endl;
		std::cout << "Thread[" << std::this_thread::get_id() << "]receive a message from my pipe[" << fd << "]: " << std::endl;
		std::cout << "Size of a is " << a->size() << std::endl;
		for (int i = 0; i < a->size(); i++)
		{
			std::cout << "[" << i << "]: " << a->at(i) << std::endl;
		}

	}
}

int main() {

	std::cout << "Main Thread id [" << std::this_thread::get_id() << "]..." << std::endl;
	//TcpServer tcp;

	//pipetest

	int m_pipe[2];
	
	if (pipe(m_pipe) == -1) {

		std::cout << "???" << std::endl;

	}

	int mypipeReadFd = m_pipe[0];
	int mypipeWriteFd = m_pipe[1];

	std::thread t1([mypipeReadFd] {

		struct event_base* m_base;
		m_base = event_base_new();
		struct event m_pipeEvent;
		event_set(&m_pipeEvent, mypipeReadFd, EV_READ | EV_PERSIST, pipe_cb, &m_pipeEvent);
		event_base_set(m_base, &m_pipeEvent);
		event_add(&m_pipeEvent, 0);

		event_base_dispatch(m_base);

		event_base_free(m_base);

		std::cout << "Thread[" << std::this_thread::get_id() << "] is died..." << std::endl;
	});

	t1.detach();

	//myTXT m;
	std::string s;

	while (1) {

		s = { 0 };

		std::cin >> s;

		if (s != "close")
		{
			write(mypipeWriteFd, (void*) & s, sizeof(s));
		}
		else {
			write(mypipeWriteFd, (void*)&s, sizeof(s));
			break;
		}
	}
	
	std::this_thread::sleep_for(std::chrono::seconds(1));

	close(m_pipe[0]);
	close(m_pipe[1]);

	return 0;

}
